package com.zj.base.utils;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.os.Looper;
import android.text.TextUtils;
import android.widget.Toast;

import com.zj.base.base_act.IBaseApplication;

/**
 * Created by zhaojie on 2017/10/9.
 */
public class ToastUtils {

    /**
     * 全局Toast  ,ToastUtils.showText("message",context);
     */

    @SuppressLint("StaticFieldLeak")
    private static Context c;
    private static Toast toast_utils;

    private ToastUtils() {

    }

    public static void init(Context context) {
        c = context;
    }

    @SuppressLint("ShowToast")
    public static void show(String text) {
        if (TextUtils.isEmpty(text)) {
            return;
        }
        if (c == null) {
            c = IBaseApplication.getAppContext();
        }
        if (toast_utils == null) {
            toast_utils = Toast.makeText(c, text, Toast.LENGTH_SHORT);
        }
        toast_utils.setText(text);
        toast_utils.show();
    }

    public static void showSafeToast(final Activity activity, final String text) {
        if (Looper.myLooper() == Looper.getMainLooper()) {
            show(text);
        } else {
            activity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    show(text);
                }
            });
        }
    }

    public static void showSafeToast(final Context context, final String text) {
        if (Looper.myLooper() == Looper.getMainLooper()) {
            show(text);
        } else {
            if (context instanceof Activity) {
                ((Activity) context).runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        show(text);
                    }
                });
            }
        }
    }

}